<?php

include_once "ActionBlock.php";

/**
 * @author sskrobotov
 */
class RequestProcessor {

    static private $instance;

    static function instance() {
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }
        return self::$instance;
    }

    private function __construct() {$this->init();}
    private function __clone() {}
    
    /* */
    
    private $xslt = false;
    
    private function init() {
        if (array_key_exists("xslt", $_GET)) {
            $this->xslt = true;
            header('Content-Type: text/xml');
            $this->append('<?xml version="1.0" encoding="utf-8"?>');
        }
    }
    
    private function append($res) {
        echo $res;
    }
    
    private static function factory($path, $clazz) {
        if (include_once $path . '/' . $clazz . '.php') {
            $action = new $clazz;
            if (!$action instanceof ActionBlock) {
                throw new Exception ("Class [$clazz] not instance of ActionBlock class");
            }
            return $action;
        } else {
            throw new Exception ("Class [$clazz] not found in [$path]");
        }
    }

    public function call($path, $clazz, $xsl) {
        $action = self::factory($path, $clazz);
        $action->run();
        $res = $action->getResponse();
        
        if (!$this->xslt) {
            $xslDoc = new DOMDocument();
            $xslDoc->load($path . '/' . $xsl);
            
            $xmlDoc = new DOMDocument();
            $xmlDoc->loadXML($res);
    
            $proc = new XSLTProcessor();
            $proc->importStylesheet($xslDoc);
            $this->append($proc->transformToXML($xmlDoc));
        } else {
            $this->append($res);
        }
    }
}

$rp = RequestProcessor::instance();
?>